package cn.bdqn.controller.course;

import cn.bdqn.dto.LoginUser;
import cn.bdqn.pojo.course.CourseVideo;
import cn.bdqn.service.course.CourseVideoService;
import cn.bdqn.utils.FileUpload;
import cn.bdqn.utils.Json;
import cn.hutool.core.io.file.FileSystemUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

@RestController
@CrossOrigin
@RequestMapping("/api")
public class CourseVideoController {
    @Autowired
    CourseVideoService videoService;

    /**
     * 查询所有视频信息
     * @return  返回json对象
     */
    @GetMapping("/selectVideoAll")
    public Json selectVideoAll(){
        List<CourseVideo> courseVideos = videoService.selectAllCourseVideo();
        Json json=new Json();
        json.setData(courseVideos);
        return json;
    }

    /**
     * 上传视频文件
     * @param videoFile 视频文件对象
     * @param courseId  课程id
     * @param catalogId 目录id
     * @param realPath  文件存放绝对路径
     * @param videoPath 视频相对路径
     * @return  返回json对象
     */
    @PreAuthorize("hasAuthority('course:management')")
    @PostMapping("/uploadVideo")
    public Object uploadVideo(@RequestParam("videoFile") MultipartFile videoFile,@RequestParam("courseId") Integer courseId,@RequestParam("catalogId") Integer catalogId,@Value("${prop.realPath}") String realPath,@Value("${prop.upload-video}") String videoPath){
        //检查课程id是否为空
        if (null == courseId || courseId <0) {
            return new Json(400,"课程id不能为空");
        }
        //检查目录id是否为空
        if (null == catalogId || catalogId <0) {
            return new Json(400,"目录id不能为空");
        }

        FileUpload fileUpload = new FileUpload(videoPath+"/"+courseId+"/"+catalogId);

        try {
            String url = fileUpload.upload(realPath, videoFile);
            if (null == url) {
                return new Json(400,"未找到文件存放地址");
            }else {
                System.out.println(url);
                return new Json(200,"上传成功",url);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new Json(400,"上传失败");
        }
    }

    /**
     * 创建课程视频信息
     * @param courseVideo   视频信息对象
     * @return  返回json对象
     */
    @PreAuthorize("hasAuthority('course:management')")
    @PostMapping("/creatCourseVideo")
    public Object creatCourseVideo(@RequestBody CourseVideo courseVideo){
        System.out.println(courseVideo);
        //检查视频信息是否为空
        if (null == courseVideo || courseVideo.getCourseVideoName() == null) {
            return new Json(400,"视频名称不能为空");
        }

        //获取登录用户id
        LoginUser principal = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Integer userid = principal.getUser().getUserId();
        if (Objects.isNull(userid)) {
            throw new RuntimeException("用户未登录");
        }

        courseVideo.setCourseVideoUserId(userid);

        Integer integer = videoService.insertCourseVideo(courseVideo);

        if(integer < 0){
            return new Json(400,"添加失败");
        }else {
            return new Json(200,"添加成功");
        }
    }

    /**
     * 根据视频id删除视频信息
     * @param videoId   视频id
     * @param url   视频文件相对路径
     * @param realPath  文件存放绝对路径
     * @return  返回json对象
     */
    @PreAuthorize("hasAuthority('course:management')")
    @DeleteMapping("/deleteCourseVideoById")
    public Object deleteCourseVideoById(Integer videoId,String url,@Value("${prop.realPath}")String realPath){
        Json json = null;
        //检查视频id是否为空
        if (null == videoId) {
            json = new Json(400,"视频id不能为空");
        }else if (null == url||url.trim().length() == 0){
            //检查视频路径是否为空
            json = new Json(400,"视频路径不能为空");
        }

        if (null == json) {
            //删除视频文件
            boolean b = FileSystemUtils.deleteRecursively(new File(realPath  + url));
            //检查是否删除成功
            if (b) {
                //删除数据库中的数据
                Integer integer = videoService.deleteCourseVideoById(videoId);
                if(integer < 0){
                    return new Json(400,"删除失败");
                }else {
                    return new Json(200,"删除成功");
                }
            }else {
                json = new Json(400,"视频删除失败");
            }
        }
        return json;
    }

}
